package rpc

import (
	"context"
	proto "gykjgit.dccnet.com.cn/chain/proto/swarm"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
	"gykjgit.dccnet.com.cn/chain/swarm/model"
)

// System 区块链中系统相关操作服务
type StackServer struct {
}

// Deploy 部署新的堆栈或更新现有堆栈
//
// tail 代表是否实时输出命令执行的日志信息
func (s *StackServer) Deploy(_ context.Context, in *proto.ReqCompose) (*proto.Response, error) {
	c, err := model.NewCompose(in.Compose)
	if nil != err {
		return &proto.Response{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	err = client.Obtain().Stack().Deploy(c, in.StackName)
	if nil != err {
		return &proto.Response{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.Response{Code: proto.Code_success}, nil
}

// List 列出现有堆栈
func (s *StackServer) List(_ context.Context, _ *proto.Request) (*proto.RespStackList, error) {
	stacks, err := client.Obtain().Stack().List()
	if nil != err {
		return &proto.RespStackList{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespStackList{Code: proto.Code_success, Stacks: stacks}, nil
}

// Process 列出堆栈中的任务
func (s *StackServer) Process(_ context.Context, in *proto.ReqStack) (*proto.RespStackProcesses, error) {
	ps, err := client.Obtain().Stack().Process(in.StackName)
	if nil != err {
		return &proto.RespStackProcesses{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespStackProcesses{Code: proto.Code_success, StackProcesses: ps}, nil
}

// Services 列出堆栈中的服务
func (s *StackServer) Services(_ context.Context, in *proto.ReqStack) (*proto.RespStackServices, error) {
	ss, err := client.Obtain().Stack().Services(in.StackName)
	if nil != err {
		return &proto.RespStackServices{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespStackServices{Code: proto.Code_success, Services: ss}, nil
}

// Remove 删除一个或多个堆栈
func (s *StackServer) Remove(_ context.Context, in *proto.ReqStack) (*proto.Response, error) {
	err := client.Obtain().Stack().Remove(in.StackName)
	if nil != err {
		return &proto.Response{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.Response{Code: proto.Code_success}, nil
}
